package com.yunrui.device.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yunrui.device.entity.Cabinet;
import com.yunrui.device.entity.CabinetSlot;
import com.yunrui.device.entity.CabinetType;
import com.yunrui.device.mapper.CabinetMapper;
import com.yunrui.device.mapper.CabinetSlotMapper;
import com.yunrui.device.mapper.CabinetTypeMapper;
import com.yunrui.device.service.CabinetService;
import com.yunrui.device.vo.CabinetVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CabinetServiceImpl extends ServiceImpl<CabinetMapper, Cabinet> implements CabinetService {

    @Autowired
    private CabinetTypeMapper cabinetTypeMapper;

    @Autowired
    private CabinetSlotMapper cabinetSlotMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean saveWithSlots(Cabinet cabinet) {
        // 1️⃣ 判断 cabinetCode 是否存在
        QueryWrapper<Cabinet> query = new QueryWrapper<>();
        query.eq("cabinet_code", cabinet.getCabinetCode());
        if (this.count(query) > 0) {
            throw new RuntimeException("柜机编号已存在！");
        }
    
        System.out.println("接收到的柜机数据：" + cabinet);
        System.out.println("尝试查询类型ID：" + cabinet.getTypeId());
        
        // 检查类型ID是否存在
        CabinetType type = cabinetTypeMapper.selectById(cabinet.getTypeId());
        System.out.println("查询到的类型：" + type);
        
        if (type == null) {
            throw new RuntimeException("柜机类型不存在，typeId=" + cabinet.getTypeId());
        }
    
        // 2️⃣ 保存柜机
        boolean saved = this.save(cabinet);
        System.out.println("保存后柜机ID：" + cabinet.getId());
        if (!saved) return false;
    
        // 3️⃣ 自动生成插槽
        int count = type.getSlotCount();
        System.out.println("开始生成插槽，数量: " + count);
    
        for (int i = 1; i <= count; i++) {
            CabinetSlot slot = new CabinetSlot();
            slot.setCabinetId(cabinet.getId());
            slot.setSlotNumber(i);
            slot.setStatus(0); // 空闲
            cabinetSlotMapper.insert(slot);
            System.out.println("成功插入插槽 #" + i);
        }
    
        System.out.println("插槽生成完成！共生成 " + count + " 个插槽");
        return true;
    }
    
    @Override
    public List<CabinetVO> getWithTypeName() {
        return baseMapper.selectWithTypeName();
    }
}